//
//  GKCustomAlertView.m
//  jinwan
//
//  Created by 王尧 on 2017/6/6.
//  Copyright © 2017年 wy. All rights reserved.
//

#import "GKCustomAlertView.h"
#import "UIView+GKBounceAnimal.h"
#import "constraintHelper.h"
@interface GKCustomAlertView ()

/** */
@property (nonatomic, strong) UIButton  *backgroundButton;

@property (nonatomic, copy) void (^handler)(GKCustomAlertView *alertView, NSInteger buttonIndex);

@end

@implementation GKCustomAlertView

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message sureTitle:(NSString *)sureTitle cancleTitle:(NSString *)cancleTitle handler:(void (^)(GKCustomAlertView *alertView, NSInteger buttonIndex))block
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0];
        
        self.titleLable.text = title;
        self.contentLable.text = message;
        [self.sureButton setTitle:sureTitle forState:UIControlStateNormal];
        [self.cancelButton setTitle:cancleTitle forState:UIControlStateNormal];
        if (block) self.handler = block;
        [self createConstraintsWithTitle:title sureTitle:sureTitle cancleTitle:cancleTitle];
    }
    return self;
}

- (instancetype)initWithTextFieldViewTitle:(NSString *)title sureTitle:(NSString *)sureTitle cancleTitle:(NSString *)cancleTitle  handler:(void (^)(GKCustomAlertView *alertView, NSInteger buttonIndex))block
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
        
        self.titleLable.text = title;
        [self.sureButton setTitle:sureTitle forState:UIControlStateNormal];
        [self.cancelButton setTitle:cancleTitle forState:UIControlStateNormal];
        if (block) self.handler = block;
        
        [self addSubview:self.backgroundButton];
        [self.backgroundButton addSubview:self.alertView];
        [self.alertView addSubview:self.titleLable];
        [self.alertView addSubview:self.passwordView];
        [self.alertView addSubview:self.cancelButton];
        [self.alertView addSubview:self.textViewSureButton];
        
        [self textFieldViewCreateConstraintsWithTitle:title sureTitle:sureTitle cancleTitle:cancleTitle];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

#pragma mark ---- 键盘监听 ----
- (void)keyboardWillShow: (NSNotification *)notification
{
    CGFloat alertViewBottom_offset = - 326 - 10;
    [self.alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundButton.mas_centerX);
        make.bottom.equalTo(self.backgroundButton.mas_bottom).offset(alertViewBottom_offset);
        make.left.equalTo(self.backgroundButton.mas_left).offset(52);
        make.right.equalTo(self.backgroundButton.mas_right).offset(-52);
    }];
    [UIView animateWithDuration:0.5 animations:^{
        [self layoutIfNeeded];
    }];
}

- (void)keyboardWillHide: (NSNotification *)notification
{
    [self.alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundButton.mas_centerX);
        make.centerY.equalTo(self.backgroundButton.mas_centerY);
        make.left.equalTo(self.backgroundButton.mas_left).offset(52);
        make.right.equalTo(self.backgroundButton.mas_right).offset(-52);
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        [self layoutIfNeeded];
    }];
}

#pragma mark ---- Constraints ----
- (void)createConstraintsWithTitle:(NSString *)title sureTitle:(NSString *)sureTitle cancleTitle:(NSString *)cancleTitle
{
    [self addSubview:self.backgroundButton];
    [self.backgroundButton addSubview:self.alertView];
    [self.alertView addSubview:self.titleLable];
    [self.alertView addSubview:self.contentLable];

    [self.backgroundButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    CGFloat alertViewOffset = [constraintHelper autoHeight:52];
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundButton.mas_centerX);
        make.centerY.equalTo(self.backgroundButton.mas_centerY);
        make.left.equalTo(self.backgroundButton.mas_left).offset(alertViewOffset);
        make.right.equalTo(self.backgroundButton.mas_right).offset(-alertViewOffset);
    }];
    
    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.alertView.mas_top).offset(16);
        make.left.equalTo(self.alertView.mas_left).offset(16);
        make.right.equalTo(self.alertView.mas_right).offset(-16);
    }];
    
    /** 判断title */
    if (title.length > 0) {
        [self.contentLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLable.mas_bottom).offset(14);
            make.left.greaterThanOrEqualTo(self.titleLable);
            make.right.lessThanOrEqualTo(self.titleLable);
            make.centerX.equalTo(self.titleLable);
        }];
    } else {
        [self.contentLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.alertView.mas_top).offset(20);
            make.left.greaterThanOrEqualTo(self.titleLable);
            make.right.lessThanOrEqualTo(self.titleLable);
            make.centerX.equalTo(self.titleLable);
        }];
    }
    
    
    /** 判断button */
    if (sureTitle.length > 0 && cancleTitle.length > 0) {
        
        [self.alertView addSubview:self.cancelButton];
        [self.alertView addSubview:self.sureButton];
        
        NSArray *array = @[self.cancelButton, self.sureButton];
        
        [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:7 leadSpacing:16 tailSpacing:16];
        [array mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentLable.mas_bottom).offset(14);
            make.height.equalTo(@32);
            make.bottom.equalTo(self.alertView.mas_bottom).offset(-16);
        }];

        
    } else if (sureTitle.length > 0 && cancleTitle.length == 0) {
        
        [self.alertView addSubview:self.sureButton];
        
        [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentLable.mas_bottom).offset(14);
            make.height.equalTo(@32);
            make.left.equalTo(self.alertView.mas_left).offset(70);
            make.right.equalTo(self.alertView.mas_right).offset(-70);
            make.bottom.equalTo(self.alertView.mas_bottom).offset(-16);
        }];
        
    } else if (sureTitle.length == 0 && cancleTitle.length > 0) {
        
        [self.alertView addSubview:self.cancelButton];
        [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentLable.mas_bottom).offset(14);
            make.height.equalTo(@32);
            make.left.equalTo(self.alertView.mas_left).offset(70);
            make.right.equalTo(self.alertView.mas_right).offset(-70);
            make.bottom.equalTo(self.alertView.mas_bottom).offset(-16);
        }];
    }
}


- (void)textFieldViewCreateConstraintsWithTitle:(NSString *)title sureTitle:(NSString *)sureTitle cancleTitle:(NSString *)cancleTitle
{
    [self.backgroundButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    CGFloat alertViewOffset = [constraintHelper autoHeight:52];
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundButton.mas_centerX);
        make.centerY.equalTo(self.backgroundButton.mas_centerY);
        make.left.equalTo(self.backgroundButton.mas_left).offset(alertViewOffset);
        make.right.equalTo(self.backgroundButton.mas_right).offset(-alertViewOffset);
    }];
    
    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.alertView.mas_top).offset(18);
        make.left.equalTo(self.alertView.mas_left).offset(16);
        make.right.equalTo(self.alertView.mas_right).offset(-16);
    }];
    
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLable.mas_bottom).offset(8);
        make.left.right.equalTo(self.titleLable);
    }];
    
    NSArray *array = @[self.cancelButton, self.textViewSureButton];
    
    [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:7 leadSpacing:16 tailSpacing:16];
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordView.mas_bottom).offset(8);
        make.height.equalTo(@32);
        make.bottom.equalTo(self.alertView.mas_bottom).offset(-16);
    }];
}

#pragma mark -- 更新界面 --

- (void)updateCustomAlertWithErrorMessage:(NSString *)msg
{
    self.passwordView.hidden = YES;
    self.contentLable.textAlignment = NSTextAlignmentCenter;
    self.titleLable.textColor = [UIColor redColor];
    self.titleLable.text = @"交易失败";
    self.contentLable.text = @"哎呀，手慢了！\n你的最爱被人抢先了，再瞟一个？";
    [self.textViewSureButton setTitle:@"再瞟一个" forState:UIControlStateNormal];
    
    [self.alertView addSubview:self.contentLable];
    
    [self.passwordView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLable.mas_bottom).offset(8);
        make.left.right.equalTo(self.titleLable);
        make.height.equalTo(@42);
    }];
    
    [self.contentLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLable.mas_bottom).offset(8);
        make.left.right.equalTo(self.titleLable);
        make.bottom.equalTo(self.passwordView.mas_bottom);
    }];
}

#pragma mark ---- 显示弹框 ----
- (void)alertShow
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [self.alertView beginAnimationWithBegainScale:1.2 middleScale:1.0 duration:0.2];
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    }];
    [keyWindow addSubview:self];
}

#pragma mark ---- 取消按钮 ----
- (void)cancelAction:(UIButton *)sender
{
    
    if (self.handler) {
        self.handler(self, 0);
    }
    [self removeFromSuperview];
}

- (void)sureAction:(UIButton *)sender
{
    if (self.handler) {
        self.handler(self, 1);
    }
    [self removeFromSuperview];
}

#pragma mark ---- 密码弹框确认事件 ----
- (void)textViewSureAction:(UIButton *)sender
{
    if (self.handler) {
        self.handler(self, 1);
    }
}

- (void)dismissAlertView
{
    [self removeFromSuperview];
}


#pragma mark - 便利构造器方法

+ (void)showSureAlertWithMessage:(NSString *)message completionBlock:(void (^)())completionBlock
{
    GKCustomAlertView *alert = [[GKCustomAlertView alloc] initWithTitle:@"温馨提示" message:message sureTitle:@"确定" cancleTitle:nil handler:^(GKCustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex) {
            if (completionBlock) {
                completionBlock();
            }
        }
    }];
    alert.contentLable.textAlignment = NSTextAlignmentCenter;
    [alert alertShow];
}

+ (void)showCancleAlertWithMessage:(NSString *)message completionBlock:(void (^)())completionBlock
{
    GKCustomAlertView *alert = [[GKCustomAlertView alloc] initWithTitle:@"温馨提示" message:message sureTitle:nil cancleTitle:@"取消" handler:^(GKCustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex) {
            if (completionBlock) {
                completionBlock();
            }
        }
    }];
    alert.contentLable.textAlignment = NSTextAlignmentCenter;
    [alert alertShow];
}

+ (void)showAlertWithMessage:(NSString *)message completionBlock:(void (^)(NSUInteger))completionBlock
{
    GKCustomAlertView *alert = [[GKCustomAlertView alloc] initWithTitle:@"温馨提示" message:message sureTitle:@"确定" cancleTitle:@"取消" handler:^(GKCustomAlertView *alertView, NSInteger buttonIndex) {
        if (completionBlock) {
            completionBlock(buttonIndex);
        }
    }];
    alert.contentLable.textAlignment = NSTextAlignmentCenter;
    [alert alertShow];
}

+ (void)showAlertWithMessage:(NSString *)message delayAfter:(CGFloat)delayTime
{
    GKCustomAlertView *alert = [[GKCustomAlertView alloc] initWithTitle:@"温馨提示" message:message sureTitle:nil cancleTitle:nil handler:^(GKCustomAlertView *alertView, NSInteger buttonIndex) {
        
    }];
    alert.contentLable.textAlignment = NSTextAlignmentCenter;
    [alert alertShow];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert removeFromSuperview];
    });
}

+ (void)showAlertWithMessage:(NSString *)message
{
    [self showAlertWithMessage:message delayAfter:1.5];
}

+ (GKCustomAlertView *)showTradePasswordAlertWithMessage:(NSString *)message completionBlock:(void (^)(GKCustomAlertView *alertView, NSInteger buttonIndex))completionBlock
{
    GKCustomAlertView *alert = [[GKCustomAlertView alloc] initWithTextFieldViewTitle:@"请输入交易密码" sureTitle:@"确认" cancleTitle:@"取消" handler:^(GKCustomAlertView *alertView, NSInteger buttonIndex) {
        if (completionBlock) {
            completionBlock(alertView, buttonIndex);
        }
    }];
    [alert alertShow];
    return alert;
}


#pragma mark ---- getter ----
- (UIButton *)backgroundButton
{
    if (!_backgroundButton) {
        _backgroundButton = [[UIButton alloc] init];
//        _backgroundButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    }
    return _backgroundButton;
}

- (UIView *)alertView
{
    if (!_alertView) {
        _alertView = [[UIView alloc] init];
//        _alertView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0];
        _alertView.backgroundColor = [UIColor whiteColor];
        _alertView.layer.cornerRadius = 10;
    }
    return _alertView;
}

- (UILabel *)contentLable
{
    if (!_contentLable) {
        _contentLable = [[UILabel alloc] init];
        _contentLable.font = [UIFont systemFontOfSize:14];
        _contentLable.textColor = [UIColor custom_color:@"#333333"];
        _contentLable.numberOfLines = 0;
        NSString *content = [NSString stringWithFormat:@"1、资金同卡进出，只支持绑定一张银行卡。如需更换银行卡，请联系客服\n 2、若遇到银行卡充值受限，建议您在PC端通过网银支付充值"];
        _contentLable.text = content;
    }
    return _contentLable;
}

- (UILabel *)titleLable
{
    if (!_titleLable) {
        _titleLable = [[UILabel alloc] init];
        _titleLable.textAlignment = NSTextAlignmentCenter;
        _titleLable.textColor = [UIColor custom_color:@"#333333"];
        _titleLable.font = [UIFont systemFontOfSize:18];
        _titleLable.text = @"提示";
    }
    return _titleLable;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.backgroundColor = [UIColor whiteColor];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _cancelButton.layer.cornerRadius = 5;
        _cancelButton.layer.borderWidth = 1;
        _cancelButton.layer.borderColor = [UIColor custom_color:@"#CA374F"].CGColor;
        [_cancelButton setTitleColor:[UIColor custom_color:@"#CA374F"] forState:UIControlStateNormal];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)sureButton
{
    if (!_sureButton) {
        _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureButton.backgroundColor = [UIColor custom_color:@"#CA374F"];
        _sureButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _sureButton.layer.cornerRadius = 5;
        [_sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sureButton setBackgroundImage:[UIImage imageNamed:@"116X32btn"] forState:UIControlStateNormal];
        [_sureButton setTitle:@"确认" forState:UIControlStateNormal];
        [_sureButton addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _sureButton;
}

- (UIButton *)textViewSureButton
{
    if (!_textViewSureButton) {
        _textViewSureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _textViewSureButton.backgroundColor = [UIColor custom_color:@"#CA374F"];
        _textViewSureButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _textViewSureButton.layer.cornerRadius = 5;
        [_textViewSureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_textViewSureButton setBackgroundImage:[UIImage imageNamed:@"116X32btn"] forState:UIControlStateNormal];
        [_textViewSureButton setTitle:@"确认" forState:UIControlStateNormal];
        [_textViewSureButton addTarget:self action:@selector(textViewSureAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _textViewSureButton;
}

- (UIView *)customView
{
    if (!_customView) {
        _customView = [[UIView alloc] init];
    }
    return _customView;
}

- (GKTransactionPasswordView *)passwordView
{
    if (!_passwordView) {
        _passwordView = [[GKTransactionPasswordView alloc] init];
        __weak typeof(self)weakSelf = self;
        _passwordView.forgetBlock = ^{
            if (weakSelf.handler) {
                weakSelf.handler(weakSelf, 2);
            }
        };
    }
    return _passwordView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}




@end
